package com.face.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.face.common.pojo.DataGridResult;
import com.face.common.pojo.FaceResult;
import com.face.mapper.TbClassMapper;
import com.face.mapper.TbMajorMapper;
import com.face.pojo.TbClass;
import com.face.pojo.TbClassExample;
import com.face.pojo.TbClassExample.Criteria;
import com.face.pojo.TbMajor;
import com.face.pojo.TbMajorExample;
import com.face.service.ClassService;

@Service
public class ClassServiceImpl implements ClassService{
	
	@Autowired
	private TbClassMapper classMapper;
	
	@Autowired
	private TbMajorMapper majorMapper;

	
	@Override
	public FaceResult add(TbClass tbClass) {
		try {
			tbClass.setCreateTime(new Date());
			tbClass.setUpdateTime(new Date());
			boolean b = this.check(tbClass);
			if(b){
				classMapper.insert(tbClass);
				return FaceResult.ok();	
			}
			return FaceResult.build(500,"此班已经存在，请查看，再添加！");
		} catch (Exception e) {
			e.printStackTrace();
			return FaceResult.build(500, "添加班级失败");
		}
	}

	@Override
	public boolean check(TbClass tbClass) {
		TbClassExample example=new TbClassExample();
		Criteria criteria = example.createCriteria();
		criteria.andMajorIdEqualTo(tbClass.getMajorId());
		List<TbClass> list = classMapper.selectByExample(example);
		for(TbClass c:list){
			if(c.getClassName().equals(tbClass.getClassName())||c.getClassNumber()==tbClass.getClassNumber()){
				return false;
			}
		}
		return true;
	}

	@Override
	public DataGridResult findClassByPage(Integer id) {
		TbClassExample example = new TbClassExample();
		 List<Integer> list = this.getMajors(id);
		 
		Criteria criteria = example.createCriteria();
		criteria.andMajorIdIn(list);
		List<TbClass> list2 = classMapper.selectByExample(example);

		DataGridResult result = new DataGridResult();
		result.setRows(list2);
		result.setTotal(list2.size());

		return result;
	}
	
	public List<Integer> getMajors(Integer id){
		TbMajorExample example=new TbMajorExample();
		com.face.pojo.TbMajorExample.Criteria criteria = example.createCriteria();
		criteria.andCollegeIdEqualTo(id);
		List<TbMajor> list = majorMapper.selectByExample(example);
		List<Integer> resuList=new ArrayList<>();
		for(TbMajor m:list){
			resuList.add(m.getId());
		}
		return resuList;
		
	}

	@Override
	public FaceResult delete(Integer[] ids) {
		try {
			for(Integer id:ids){
				classMapper.deleteByPrimaryKey(id);
			}
			return FaceResult.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return FaceResult.build(500,"删除失败");
		}
	}

	@Override
	public FaceResult update(TbClass tbClass) {
		try {
			classMapper.updateByPrimaryKeySelective(tbClass);
			return FaceResult.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return FaceResult.build(500, "修改失败");
		}
	}
	
	

}
